package cn.net.cfss.fgbp.face.manage.service;

import cn.net.cfss.fgbp.api.console.inte.ISysUserService;
import cn.net.cfss.fgbp.base.common.GlobalConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * @author wutao
 * @version 1.0
 * @date 2020/10/16 16:02
 */
@Service
@Slf4j
public class CommService {

    @Value("${tenant.role.code:zh,zh_yw}")
    private String tenantRoleCode;

    @Autowired
    private ISysUserService sysUserService;

    public Long tenantId (HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        String tenantIdStr = request.getHeader(GlobalConstants.HEADER_USER_TENANT_ID);
        if (StringUtils.isBlank(tenantIdStr) || "null".equalsIgnoreCase(tenantIdStr)) {
            return null;
        }
        Long tenantId = Long.valueOf(tenantIdStr);

        //只有租户管理员和租户业务员才返回租户id
        String[] split = tenantRoleCode.split(",");
        List<String> strings = Arrays.asList(split);
        String userIdStr = request.getHeader("Authorization-UserId");
        Long userId = Long.valueOf(userIdStr);
        List<String> roleCodeByUid = sysUserService.getRoleCodeByUid(userId);
        for (String s : roleCodeByUid) {
            boolean contains = strings.contains(s);
            if (contains) {
                return tenantId;
            }
        }
        return null;
    }
}
